<?php
/**
 * Message represents an message of a chip 
 */
class Message extends Model {
	
	public $id;
	public $message;
	public $time;
	public $chip_id;
	public $chip_id_sender;
	public $group;

	/**
	 * constructs parent
	 */	
	function __construct() {
		parent::__contruct();
	}		

	/** 
	 * Gets a list of message's by given chip_id
	 * @param chip_id The id of the chip
	 * @return List of message's 
	 */		
	function getByChipId($chip_id) {
		$sth = $this->db->prepare('SELECT m.* FROM message m 
								   LEFT JOIN account_chip ac ON ac.chip_id = m.chip_id
								   LEFT JOIN account a ON a.id = ac.account_id								   
								   WHERE a.id = :account_id');
		$sth->execute(array(':chip_id' => $chip_id));
		return $sth->fetchAll(PDO::FETCH_CLASS, 'Message');		
	}
	
	/** 
	 * Gets a list of message's by given chip_id
	 * @param chip_id The id of the chip
	 * @return List of message's 
	 */			
	function getBySender($chip_id) {
		$sth = $this->db->prepare('SELECT * FROM message 
							  	   WHERE (chip_id_sender = :chip_id_sender 
							  	   AND chip_id = :chip_id OR 
							  	   chip_id_sender = :chip_id AND chip_id = :chip_id_sender)
								   ORDER BY id');
		$sth->execute(array(':chip_id_sender' => Session::get('chip_id'), ':chip_id' => $chip_id));
		return $sth->fetchAll(PDO::FETCH_ASSOC);			
	}
	

	/** 
	 * Gets a list of message's by given chip_id
	 * @param chip_id The id of the chip
	 * @return List of message's 
	 */			
	function getByAccount() {
		$sth = $this->db->prepare('SELECT c.* FROM chip c 
								   LEFT JOIN account_chip ac ON ac.chip_id = c.id
								   LEFT JOIN account a ON a.id = ac.account_id								   
								   WHERE a.id = :account_id');
		$sth->execute(array(':account_id' => Session::get('account_id')));
		$chips =  $sth->fetchAll(PDO::FETCH_CLASS, 'Chip');	

		// Build query
	 	$query = 'SELECT m.*, c.name FROM message m
	 			  LEFT JOIN chip c ON c.id = m.chip_id_sender
				  WHERE m.group = 1
				  AND (';
	 	$i = 0;	 	
	 	foreach($chips as $chip) {
	 		if($i == 0) {
	 			$query .= ' m.chip_id_sender = ' . $chip->id;	 			
	 		} else {
	 			$query .= ' OR m.chip_id_sender = ' . $chip->id;
	 		}
	 		$i++;
	 	}
	 	$query .= ')';
	 	$result = $this->db->query($query);
	 	return $result->fetchAll(PDO::FETCH_CLASS, 'Message');
	
	}
	
	/**  
	 * Save's an Message object
	 * @return true if saved succesfully else return false 
	 */		
	function save() {
		if($this->id) {
			if($this->db->update('message', $this)) {
				return true;
			};
		} else {
			if($this->db->insert('message', $this)) {
				return true;
			};
		}
		return false;
	}
}
